package xml;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 孙许
 * @date 2018-04-20
 * @description
 */
public class ReadxmlByJDom {
    private List<Book> books;
    private Book book;
    private SAXBuilder builder = new SAXBuilder();

    public List<Book> getBooks(File fileName) throws Exception {
        Document document = builder.build(fileName);
        // 获取根节点
        Element root = document.getRootElement();
        // 获取根节点的子节点，返回子节点的数组
        List<Element> bookNodeList = root.getChildren();
        books = new ArrayList<>();
        for (Element bookElement : bookNodeList) {
            book = new Book();
            // 获取bookElement的属性
            List<Attribute> bookElementAttributes = bookElement.getAttributes();
            for (Attribute bookElementAttribute : bookElementAttributes) {
                if ("id".equals(bookElementAttribute.getName())) {
                    String id = bookElementAttribute.getValue();
                    book.setId(Integer.parseInt(id));
                }
            }
            // 获取bookElement的子节点
            List<Element> children = bookElement.getChildren();
            for (Element child : children) {
                if ("name".equals(child.getName())) {
                    String name = child.getValue();
                    book.setName(name);
                }
                if ("author".equals(child.getName())) {
                    String author = child.getValue();
                    book.setAuthor(author);
                }
                if ("year".equals(child.getName())) {
                    String year = child.getValue();
                    book.setYear(Integer.parseInt(year));
                }
                if ("price".equals(child.getName())) {
                    String price = child.getValue();
                    book.setPrice(Double.parseDouble(price));
                }
            }
            books.add(book);
            book = null;
        }
        return books;
    }
}
